//
//  VistaInAppPurchaseManager.m
//  MyApp
//
//  Created by woshisha on 2019/1/21.
//


#import "VistaInAppPurchaseManager.h"

@interface VistaInAppPurchaseManager ()<SKProductsRequestDelegate, SKPaymentTransactionObserver>
    
    
@end

@implementation VistaInAppPurchaseManager
    {
        SKProduct *myProduct;
        
    }
    
    
    static VistaInAppPurchaseManager *manager = nil;
    
+(instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (manager == nil) {
            manager = [[VistaInAppPurchaseManager alloc]init];
        }
        
    });
    return manager;
}
    
#pragma mark ------  public Methods
-(void)requestProductWithID:(NSString *)productID{
    if (productID.length > 0) {
        SKProductsRequest *productRequest = [[SKProductsRequest alloc]initWithProductIdentifiers:[NSSet setWithObject:productID]];
        productRequest.delegate = self;
        [productRequest start];
        
    }else{
        
        NSLog(@"productID为空");
    }
    
    
}
    
-(BOOL)purchaseProudct:(SKProduct *)skProduct{
    
    if (skProduct != nil) {
        if ([SKPaymentQueue canMakePayments]) {
            SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:skProduct];
            payment.quantity = self.quantity;
            [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
            [[SKPaymentQueue defaultQueue] addPayment:payment];
            return YES;
        }else{
            NSLog(@"失败，用户禁止应用内付费购买.");
        }
    }
    return NO;
}
    
#pragma mark ------  SKProductsRequestDelegate
    
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSArray *productArr = response.products;
    if (productArr.count > 0) {
        myProduct = [productArr objectAtIndex:0];
        [_delegate receiveProductInfo:myProduct];
    }else{
        NSLog(@"无法购买商品信息，购买失败");
        [_delegate receiveProductInfo:myProduct];
    }
}
    
#pragma mark ------  SKPaymentTransactionObserver
    
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
            case SKPaymentTransactionStatePurchasing://商品添加进列表
            NSLog(@"商品:%@被添加进购买列表",myProduct.localizedTitle);
            break;
            case SKPaymentTransactionStatePurchased://交易成功
            [self completeTransaction:transaction];
            break;
            case SKPaymentTransactionStateFailed://交易失败
            [self failedTransaction:transaction];
            NSLog(@"交易失败");
            //发送通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"failNotification" object:self userInfo:nil];
            break;
            case SKPaymentTransactionStateRestored://已购买过该商品
            break;
            
            case SKPaymentTransactionStateDeferred://交易延迟
            default:
            break;
        }
    }
}
    
    
#pragma mark ---- private Methods
    
-(void)completeTransaction:(SKPaymentTransaction *)transaction{
    NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
    [_delegate successfulPurchaseOfId:transaction.payment.productIdentifier andReceipt:receiptData];
    //   [[NSUserDefaults standardUserDefaults] setObject:receiptData forKey:@"receiptData"];
    //    [[NSUserDefaults standardUserDefaults] synchronize];
    [[SKPaymentQueue defaultQueue]finishTransaction:transaction];
}
    
- (void)failedTransaction:(SKPaymentTransaction *)transaction{
    if (transaction.error.code != SKErrorPaymentCancelled && transaction.error.code != SKErrorUnknown) {
        [_delegate failedPurchaseWithError:transaction.error.localizedDescription];
    }else{
        [_delegate failedPurchaseWithError:@"交易失败"];
    }


    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
    
-(void)dealloc{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
    
    @end
